package com.example.cd5160866.urlapp.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.text.TextUtils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;

public class PhotoTakerNew implements Serializable {
    private static final long serialVersionUID = 1L;
    private int cameraRequestCode = 0;
    private int albumRequestCode = 1;
    /**
     * 原图
     */
    private String originFilePath;
    /**
     * 压缩后的图片
     */
    private String filePath;
    /**
     * 网络url
     */
    private String networkUrl;

    private int maxSize = ImageUtil.MAX_SIZE;

    public PhotoTakerNew() {
    }

    public PhotoTakerNew(int requestCode) {
        setRequestCode(requestCode);
    }

    /**
     * 必须是偶数
     */
    public void setRequestCode(int requestCode) {
        cameraRequestCode = requestCode;
        albumRequestCode = requestCode + 1;
    }

    public void setMaxSize(int maxSize) {
        this.maxSize = maxSize;
    }

    public int getRequestCode() {
        return getCameraRequestCode();
    }

    public int getCameraRequestCode() {
        return cameraRequestCode;
    }

    public int getAlbumRequestCode() {
        return albumRequestCode;
    }

    /**
     * 拍照
     */
    public void takePhoto(Activity activity) {
        onCameraClick(activity);
    }

    public void takePhoto(Fragment fragment) {
        onCameraClick(fragment);
    }

    /**
     * 从相机选照片
     */
    public void pickPhoto(Activity activity) {
        onAlbumClick(activity);
    }

    public void pickPhoto(Fragment fragment) {
        onAlbumClick(fragment);
    }

    /**
     * 最好在子线程中调用
     */
    private void compressPhotoFromAlbum(Context context, Intent data) {
        originFilePath = null;

        Bitmap bitmap = ImageUtil.getBitmapFromAlbum(context, data, maxSize);
        int rotate = ImageUtil.getImageOrientation(context, data.getData());
        if (rotate != 0) {
            bitmap = getRotatedBitmap(rotate, bitmap);
        }

        if (null != diskCache) {
            fileKey = String.valueOf(System.currentTimeMillis());

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            try {
                diskCache.save(fileKey, new ByteArrayInputStream(bos.toByteArray()));
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            File file = new File(FileUtil.getAutoCacheDir(Container.getContext()), System.currentTimeMillis() + ".jpg");
            filePath = file.getAbsolutePath();
            BitmapUtil.Bitmap2File(file, bitmap);
        }
    }

    private LruDiskCache diskCache;

    public void setUseDiskLruCache(LruDiskCache cache) {
        this.diskCache = cache;
    }

    private String fileKey;//压缩后图片使用DiskLruCache存储的file key

    public String getCompressPhotoFileKey() {
        return fileKey;
    }

    public File getCompressPhotoFile() {
        File file = null;
        if (null != diskCache && null != fileKey) {
            file = diskCache.get(fileKey);
        }
        return file;
    }

    /**
     * 最好在子线程中调用
     */
    private void compressPhotoFromCamera(Context context, Intent intent) {
        int rotate = 0;
        ExifHelper exif = new ExifHelper();
        try {
            exif.createInFile(originFilePath);
            exif.readExifData();
            rotate = exif.getOrientation();
        } catch (IOException e) {
            e.printStackTrace();
        }

        Bitmap bitmap = ImageUtil.getBitmapFromCamera(context, originFilePath, intent, maxSize);
        if (bitmap == null) {
            throw new RuntimeException("无法获取图片，请重新拍摄！");
        }
        if (rotate != 0) {
            bitmap = getRotatedBitmap(rotate, bitmap);
        }

        if (null != diskCache) {
            fileKey = String.valueOf(System.currentTimeMillis());

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            try {
                diskCache.save(fileKey, new ByteArrayInputStream(bos.toByteArray()));
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            File file = new File(FileUtil.getAutoCacheDir(Container.getContext()), System.currentTimeMillis() + ".jpg");
            filePath = file.getAbsolutePath();
            BitmapUtil.Bitmap2File(file, bitmap);
        }

        new File(originFilePath).delete();
        originFilePath = null;
    }

    /**
     * 最好在子线程中调用
     */
    public void compressPhoto(Context context, Intent data) {
        try {
            if (!TextUtils.isEmpty(originFilePath)) {// 相机
                compressPhotoFromCamera(context, data);
            } else {
                compressPhotoFromAlbum(context, data);
            }
        } catch (OutOfMemoryError e) {
            throw new RuntimeException("手机内存不足，重启手机试试！");
        }

    }

    private void onCameraClick(Activity activity) {
        originFilePath = null;
        if (FileUtil.hasOneSDCardMounted()) {
            File file = new File(FileUtil.getAutoCacheDir(Container.getContext()), System.currentTimeMillis() + ".jpg");
            originFilePath = file.getAbsolutePath();
            Uri uri = Uri.fromFile(file);
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            if (intent.resolveActivity(activity.getPackageManager()) != null) {
                activity.startActivityForResult(intent, getCameraRequestCode());
            } else {
                //                Toasts.shortToast("没有相机，无法拍照");
            }
        } else {
            //            Toasts.shortToast("没有sd卡，无法拍照");
        }
    }

    private void onCameraClick(Fragment fragment) {
        originFilePath = null;
        if (null == fragment.getActivity())
            return;
        if (FileUtil.hasOneSDCardMounted()) {
            File file = new File(FileUtil.getAutoCacheDir(Container.getContext()), System.currentTimeMillis() + ".jpg");
            originFilePath = file.getAbsolutePath();
            Uri uri = Uri.fromFile(file);
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            if (intent.resolveActivity(fragment.getActivity().getPackageManager()) != null) {
                fragment.startActivityForResult(intent, getCameraRequestCode());
            } else {
                //                Toasts.shortToast("没有相机，无法拍照");
            }
        } else {
            //            Toasts.shortToast("没有sd卡，无法拍照");
        }
    }

    private void onAlbumClick(Activity activity) {
        try {
            originFilePath = null;
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
            intent.setType("image/*");
            // intent.putExtra("return-data", true);
            activity.startActivityForResult(intent, getAlbumRequestCode());
        } catch (Exception e) {
            //            Toasts.shortToast("图片未找到");
        }
    }

    private void onAlbumClick(Fragment fragment) {
        if (null == fragment.getActivity())
            return;
        try {
            originFilePath = null;
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
            intent.setType("image/*");
            // intent.putExtra("return-data", true);
            fragment.startActivityForResult(intent, getAlbumRequestCode());
        } catch (Exception e) {
            //            Toasts.shortToast("图片未找到");
        }
    }

    public String getFilePath() {
        return filePath;
    }

    public String getNetworkUrl() {
        return networkUrl;
    }

    public void setNetworkUrl(String networkUrl) {
        this.networkUrl = networkUrl;
    }

    public void deleteFileIfUploaded() {
        if (!TextUtils.isEmpty(getFilePath()) && !TextUtils.isEmpty(getNetworkUrl())) {
            new File(getFilePath()).delete();
        }
    }

    public String getOriginFilePath() {
        return originFilePath;
    }

    public void setOriginFilePath(String originFilePath) {
        this.originFilePath = originFilePath;
    }

    public void setFilePath(String filePath) {
        this.filePath = filePath;
    }

    public interface OnClickReUploadListener {
        void onClickReUpload();
    }

    /**
     * Figure out if the bitmap should be rotated. For instance if the picture
     * was taken in portrait mode
     *
     * @return rotated bitmap
     */
    private Bitmap getRotatedBitmap(int rotate, Bitmap bitmap) {
        Matrix matrix = new Matrix();
        if (rotate == 180) {
            matrix.setRotate(rotate);
        } else {
            matrix.setRotate(rotate, (float) bitmap.getWidth() / 2, (float) bitmap.getHeight() / 2);
        }

        try {
            bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        } catch (OutOfMemoryError oom) {
            // You can run out of memory if the image is very large:
            // http://simonmacdonald.blogspot.ca/2012/07/change-to-camera-code-in-phonegap-190.html
            // If this happens, simply do not rotate the image and return it
            // unmodified.
            // If you do not catch the OutOfMemoryError, the Android app
            // crashes.
        }

        return bitmap;
    }

    /**
     * 是否是photoTaker 启动系统相机或相册回来的 requestCode 如果是才会处理回调的intent
     */
    public boolean isGetPhotoRequestCode(int requestCode) {
        return requestCode == cameraRequestCode || requestCode == albumRequestCode;
    }

    public interface OnImageUpLoadListener {
        void onSuccess(String url);

        void onFailed();
    }
}
